precision mediump float;

varying vec4 v_position;
varying vec2 v_texCoord;
varying vec3 v_normal;
varying vec3 v_surfaceToLight;
varying vec3 v_surfaceToView;

uniform vec4 u_lightColor;// 光照颜色
uniform vec4 u_ambient;// 环境光
uniform sampler2D u_diffuse;//漫反射
uniform vec4 u_specular;
uniform float u_shininess;
uniform float u_specularFactor;

// 高光计算  l 法向量，h 光照和相机和向量 m系数
vec4 lit(float l,float h,float m){
    return vec4(1.,
        max(l,0.),
        (l>0.)?pow(max(0.,h),m):0.,
    1.);
}

void main(){
    vec4 diffuseColor=texture2D(u_diffuse,v_texCoord);
    
    vec3 a_normal=normalize(v_normal);
    vec3 surfaceToLight=normalize(v_surfaceToLight);
    vec3 surfaceToView=normalize(v_surfaceToView);
    
    // 材质影响
    vec3 halfVector=normalize(surfaceToLight+surfaceToView);
    vec4 litR=lit(dot(a_normal,surfaceToLight),
    dot(a_normal,halfVector),u_shininess);
    
    vec4 outColor=vec4((
            u_lightColor*(diffuseColor*litR.y+diffuseColor*u_ambient+
            u_specular*litR.z*u_specularFactor)).rgb,
        diffuseColor.a);
        
        gl_FragColor=outColor;
    }